package cn.codenest.springboot.mongo.dao.impl;

import cn.codenest.springboot.mongo.dao.ItemGroupDAO;
import cn.codenest.springboot.mongo.entity.ItemGroupEntity;
import cn.codenest.springboot.mongo.entity.UserEntity;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.List;

/**
* @ClassName: ItemGroupDAOImpl
* @author: Zhihui.Liu
* @date: 2021/11/04 16:26
* @Description:
*/
@Component
public class ItemGroupDAOImpl implements ItemGroupDAO {

    @Autowired
    MongoTemplate mongoTemplate;


    @Override
    public long addUserOfGroup(String id, UserEntity userEntity) {
        Query query = new Query(Criteria.where("id").is(id));
        Update update = new Update().addToSet("users", userEntity);
        //更新查询返回的结果集的第一条数据
        UpdateResult result = mongoTemplate.updateFirst(query, update, ItemGroupEntity.class, ItemGroupEntity.COLLECTION_NAME);
        if (result != null) {
            return (int) result.getModifiedCount();
        } else {
            return 0;
        }
    }

    @Override
    public long updateUserOfGroup(String id, UserEntity userEntity) {
        Query query = new Query(Criteria.where("id").is(id).and("users.id").is(userEntity.getId()));
        Update update = new Update().set("users.$.duty", userEntity.getDuty());
        UpdateResult result = mongoTemplate.updateFirst(query, update, ItemGroupEntity.class, ItemGroupEntity.COLLECTION_NAME);
        if (result != null) {
            return (int) result.getModifiedCount();
        } else {
            return 0;
        }
    }

    @Override
    public long deleteUsersOfGroup(String id, UserEntity userEntity) {
        Query query = new Query(Criteria.where("id").is(id));
        //這裏傳入的UserEntity对象要保证查询条件有效的话，筛选的字段要有有效数据，但是其它不参与筛选的字段要设置为null，否则其它字段也会参与筛选
        Update update = new Update().pull("users", UserEntity.create(userEntity.getId(), null, null));
        //更新查询返回的结果集的第一条数据
        UpdateResult result = mongoTemplate.updateFirst(query, update, ItemGroupEntity.class, ItemGroupEntity.COLLECTION_NAME);
        if (result != null) {
            return (int) result.getModifiedCount();
        } else {
            return 0;
        }
    }

}
